package mq.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class HelloWorld {
    public final static String QUEUE_NAME = "root";
    public final static String HOST = "47.101.147.181";
    public final static String USERNAME = "root";
    public final static String PASSWORD = "root";
    public final static ConnectionFactory factory = new ConnectionFactory();
    static {
        factory.setHost(HOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
    }

    public static void send() throws IOException, TimeoutException {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //定义一个队列，队列名 是否持久化 是否排他 是否自动删除 参数
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        String message = Thread.currentThread().getName()+": "+System.currentTimeMillis();
        channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
        channel.close();
        connection.close();
    }

    public static void receive() throws IOException, TimeoutException {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME,false, deliverCallback, consumerTag -> {
            System.out.println("consumer is exited");
        });

    }
    public static void main(String[] args) throws IOException, TimeoutException {
        new Thread(()->{
            try {
                receive();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                    send();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}

